package com.apache.ibatis.configuration;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 解析Xml文件
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析配置文件
     */
    public void parse (InputStream inputStream) {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            Element rootElement = document.getRootElement();
            Attribute attributeNamespace = rootElement.attribute("namespace");
            String namespaceValue = attributeNamespace.getValue();

            List<Node> selectNodeLsit = rootElement.selectNodes("//select");
            List<Node> insertNodeLsit = rootElement.selectNodes("//insert");
            List<Node> updateNodeLsit = rootElement.selectNodes("//update");
            List<Node> deleteNodeLsit = rootElement.selectNodes("//delete");

            List<Node> allNodeList = new ArrayList<>();
            allNodeList.addAll(selectNodeLsit);
            allNodeList.addAll(insertNodeLsit);
            allNodeList.addAll(updateNodeLsit);
            allNodeList.addAll(deleteNodeLsit);

            if (!allNodeList.isEmpty()) {
                for (Node node : allNodeList) {
                    if (node instanceof Element) {
                        Element element = (Element) node;

                        String id = element.attributeValue("id");
                        String parameterType = element.attributeValue("parameterType");
                        String resultType = element.attributeValue("resultType");
                        String sqlText = element.getTextTrim();

                        MappedStatement mappedStatement = new MappedStatement();
                        mappedStatement.setId(id);
                        mappedStatement.setParameterType(parameterType);
                        mappedStatement.setResultType(resultType);
                        mappedStatement.setSql(sqlText);

                        String key = namespaceValue + "." + id;
                        configuration.getMappedStatementHashMap().put(key,mappedStatement);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
